package com.hengxinyongli.iam.remote;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import com.hengxinyongli.iam.dto.Subject;
import com.hengxinyongli.iam.entity.Department;
import com.hengxinyongli.iam.entity.Resource;
import com.hengxinyongli.iam.entity.User;
import com.hengxinyongli.iam.exception.IamServiceException;
import com.hengxinyongli.iam.filter.PermitsFilter;
import com.hengxinyongli.iam.filter.PermitsValidateChain;
import com.hengxinyongli.iam.jwt.JwtAuthService;
import com.hengxinyongli.iam.service.DepartmentService;
import com.hengxinyongli.iam.service.ResourceService;
import com.hengxinyongli.iam.service.UserService;
import com.hengxinyongli.iam.utils.UriUtils;
import com.hengxinyongli.iam.web.constant.Res;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;

import java.util.List;
import java.util.Set;

/**
 * @author magic
 * @date 2018/9/27/027 14:39
 * @version 1.0
 * Description IamServiceImpl
 */
@Service
public class IamServiceImpl implements IamService {

    private Logger logger = LoggerFactory.getLogger(IamServiceImpl.class);
    @Autowired
    JwtAuthService jwtAuthService;
    @Autowired
    UserService userService;
    @Autowired
    ResourceService resourceService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    List<PermitsFilter> permitsFilters;

    @Override
    public Subject validateToken(String token, String uri, String method,Boolean justValidateToken) {
        StopWatch stopWatch = new StopWatch("validateToken");
        stopWatch.start();
        logger.info("validateToken: {},uri: {},method: {},justValidateToken: {}",token,uri,method,justValidateToken);
        Subject subject = jwtAuthService.parseJwtToken(token);
        User user = userService.selectUserById(subject.getUserId());
        if(!Res.UN_FREEZE_STATUS.equals(user.getStatus())){
            throw new IamServiceException("当前用户已被冻结,无权限访问" + UriUtils.buildValidateUri(uri,method) + "，请联系管理员");
        }
        if(justValidateToken){
            return subject;
        }
        List<Resource> resources = resourceService.selectUserResourcesByType(subject.getUserId(), Res.BUTTON);
        Set<String> permitsSets = Sets.newLinkedHashSet();
        resources.forEach( rs -> {
            if(StringUtils.isNotEmpty(rs.getUrl())){
                permitsSets.add(rs.getUrl());
            }
        });

        PermitsValidateChain validateChain = new PermitsValidateChain(permitsFilters);
        validateChain.filter(uri,method,permitsSets);
        stopWatch.stop();
        logger.info("validateToken stopWatch info: {}", JSON.toJSONString(stopWatch));
        return subject;
    }


    @Override
    public String userLogin(String mobile, String password) {
        User loginUser = userService.getLoginUser(mobile);
        Subject subject = new Subject();
        subject.setUserId(loginUser.getId());
        subject.setUserName(loginUser.getUserName());
        subject.setMobile(loginUser.getMobile());
        subject.setUserType(loginUser.getUserType());
        subject.setDepId(loginUser.getDepId());
        subject.setDepLabel(loginUser.getDepCode());
        /*Subject subject = userService.userLogin(mobile,password, null,loginUser);*/
        return jwtAuthService.createJwtToken(subject);
    }

}
